package com.hmall.order.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.ItemClients;
import com.hmall.common.clients.UserClient;
import com.hmall.common.dto.ResultDTO;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.TbUser;
import com.hmall.order.filter.ThreadLocalUtil;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;

import com.hmall.order.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>  implements OrderService{

    @Autowired
    ItemClients itemClients;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;
    @Autowired
    UserClient userClient;

    @Override
    public Long creatOrderId(OrderRequest orderRequest) {
        /**
         * - 1）根据雪花算法生成订单id**(mybatisplus自带)**
         * - 2）商品微服务提供FeignClient，实现根据id查询商品的接口
         * - 3）根据itemId查询商品信息
         * - 4）基于商品价格、购买数量计算商品总价：totalFee
         * - 5）封装Order对象，初始status为未支付
         * - 6）将Order写入数据库tb_order表中
         */
        Item item = itemClients.findById(orderRequest.getItemId());
        long totalFee = item.getPrice() * orderRequest.getNum();
        Order order = new Order();
        /**
         * 订单状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、确认收货，交易成功 5、交易取消，订单关闭 6、交易结束
         */
        order.setStatus(1);
        order.setUserId(2L);
        order.setTotalFee(totalFee);
        order.setPaymentType(Integer.parseInt(orderRequest.getPaymentType().toString()));
        orderMapper.insert(order);

        /**
         * - 7）将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
         * - 8）将user-service的根据id查询地址接口封装为FeignClient
         * - 9）根据addressId查询user-service服务，获取地址信息
         * - 10）将地址封装为OrderLogistics对象，写入tb_order_logistics表
         * - 11）在item-service提供减库存接口，并编写FeignClient
         * - 12）调用item-service的减库存接口
         */
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(orderRequest.getItemId());
        orderDetail.setNum(Integer.valueOf(orderRequest.getNum().toString()));
        orderDetail.setName(item.getName());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetailMapper.insert(orderDetail);

        System.out.println(orderRequest.getAddressId());

        Address addressById = userClient.getAddressById(orderRequest.getAddressId());

        System.out.println("addressById = " + addressById);
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setCity(addressById.getCity());
        orderLogistics.setMobile(addressById.getMobile());
        orderLogistics.setProvince(addressById.getProvince());
        orderLogistics.setContact(addressById.getContact());
        orderLogistics.setStreet(addressById.getStreet());
        orderLogistics.setTown(addressById.getTown());

        orderLogisticsMapper.insert(orderLogistics);

        itemClients.getStock(orderRequest.getItemId(),Integer.valueOf(orderRequest.getNum().toString()));
        return order.getId();
    }

    @Override
    public Order getOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        Integer status = order.getStatus();
        if (status==1) {
            return order;
        } else {
            throw new RuntimeException();
        }
    }

    @Override
    public ResultDTO payOrder(Long orderId, PassWordPo passWordPo) {
        Long userId = ThreadLocalUtil.getUserId();
        userId = 2L;
        TbUser user = userClient.getUser(userId);
        System.out.println("user = " + user);
        String digest = DigestUtils.md5DigestAsHex(passWordPo.getPassword().getBytes());
        System.out.println("passwordMd5 = " + digest);
        if (digest.equals(user.getPassword())) {
            Order order = orderMapper.selectById(orderId);
            order.setStatus(2);
            System.out.println("order = " + order);

            Integer value = Integer.valueOf(order.getTotalFee().toString());
            user.setBalance(user.getBalance()-value);

            ResultDTO resultDTO = new ResultDTO();
            resultDTO.setSuccess(true);
            resultDTO.setMsg("成功");
            resultDTO.setData(order);
            return resultDTO;
        } else {
            ResultDTO resultDTO = new ResultDTO();
            resultDTO.setSuccess(false);
            resultDTO.setMsg("失败");
            return resultDTO;
        }
    }
}
